package com.sjf.day02.sort;

import java.util.Arrays;

/**
 * 冒泡排序
 *
 * @author <huangtang> huangtang
 * @since 2021/12/24 14:42
 **/
public class BubbleSort {
    public static void main(String[] args) {
        int[] num = {2,5,3,7,4,9,8};
        //int[] num = {2,3,4,7,8};
        //创建海量数据排序
        //int[] num = new int[100000];
        //for (int i = 0; i < 100000; i++) {
        //    num[i] = (int)(Math.random() * 100000); //生产 0 - 100000的随机数
        //}
        //long t1 = System.currentTimeMillis();
        bubble2(num);
        //long t2 = System.currentTimeMillis();
        //System.out.println("花费时间："+(t2-t1)+"ms"); // 16472ms
        //System.out.println(Arrays.toString(num));
    }

    /**
     * 对数组进行冒泡排序
     * @param num 需要排序的数组
     */
    public static void bubble(int[] num){
        boolean flag  = false;

        for (int j = 0; j < num.length-1; j++) {

            for (int i = 0; i < num.length - 1-j; i++) {

                if(num[i]>num[i+1]){
                    flag = true;//发生交换
                    swap(num,i,i+1);
                }

            }
            //System.out.printf("第%d 躺排序后的数组 %s \n",j,Arrays.toString(num));
            if(!flag){
                break; //没有进行交换，退出循环
            }else{
                flag = false; //重置flag状态
            }
        }
    }

    public static void bubble2(int[] num){
        boolean flag = false;
        for (int i = 0; i < num.length; i++) {
            for (int j = i+1; j < num.length; j++) {
                if(num[i]>num[j]){
                    flag = true;//true为发生交换
                    swap(num,i,j);
                }
            }
            if(!flag) {
                break;
            }else{
                flag = false;
            }
            System.out.println(Arrays.toString(num));
        }
    }

    /**
     * 交换数组两个数
     *
     * @param a 数组
     * @param i 交换的下标
     * @param j 交换的下标
     */
    public static void swap(int[] a, int i, int j) {
        a[i] = a[i] ^ a[j];
        a[j] = a[i] ^ a[j];
        a[i] = a[i] ^ a[j];
    }

}